package b2c

import (
	"fmt"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/config"

	"github.com/gin-gonic/gin"
)

// 列表查询
func ParknflyConfig(c *gin.Context) {

	requestData := struct {
		PushBaseUrl string `json:"push_base_url"`
		Secretkey   string `json:"secretkey"`
		Appid       string `json:"appid"`
		Status      int    `json:"status"`
		Page        int    `json:"page"`
		Limit       int    `json:"limit"`
	}{}
	c.ShouldBindJSON(&requestData)

	where := map[string]interface{}{}

	if requestData.PushBaseUrl != "" {
		where["push_base_url like ?"] = "%%" + requestData.PushBaseUrl + "%%"
	}

	if requestData.Secretkey != "" {
		where["secretkey like ?"] = "%%" + requestData.Secretkey + "%%"
	}

	if requestData.Appid != "" {
		where["appid like ?"] = "%%" + requestData.Appid + "%%"
	}

	if requestData.Status != -1 {
		where["status"] = requestData.Status
	}

	//查询信息
	var configParknflyStruct config.ConfigParknflyStruct
	var configParknflyData []config.ConfigParknflyStruct
	model.GetModelData(
		model.Db,
		configParknflyStruct.TableName(),
		&configParknflyData,
		model.QueryOptions{
			Page:       requestData.Page,
			PageSize:   requestData.Limit,
			Conditions: where,
			Debug:      true,
		},
	)

	//数据格式化
	returnData := make([]map[string]interface{}, 0)
	for _, v := range configParknflyData {
		returnData = append(returnData, map[string]interface{}{
			"id":            v.Id,
			"push_base_url": v.PushBaseUrl,
			"secretkey":     v.Secretkey,
			"appid":         v.Appid,
			"status":        v.Status,
		})
	}

	//总数查询
	count, _ := model.CountModelData(
		model.Db,
		configParknflyStruct.TableName(),
		model.QueryOptions{
			Conditions: where,
		},
	)

	controller.Success(c,
		map[string]interface{}{
			"list":        returnData,
			"total":       count,
			"pageSize":    requestData.Limit,
			"currentPage": requestData.Page,
		})
}

// 数据更新
func ParknflyConfigUpdate(c *gin.Context) {
	updateData := struct {
		Id          int    `json:"id"`
		PushBaseUrl string `json:"push_base_url"`
		Secretkey   string `json:"secretkey"`
		Appid       string `json:"appid"`
		Status      int    `json:"status"`
	}{}
	c.ShouldBindJSON(&updateData)

	var configParknflyStruct config.ConfigParknflyStruct

	if err := model.UpdateModelData(
		model.Db,
		configParknflyStruct.TableName(),
		map[string]interface{}{
			"id": updateData.Id,
		},
		map[string]interface{}{
			"push_base_url": updateData.PushBaseUrl,
			"secretkey":     updateData.Secretkey,
			"appid":         updateData.Appid,
			"status":        updateData.Status,
		},
	); err != nil {
		controller.Fail(c, fmt.Sprintf("修改失败:%s", err.Error()))
		return
	}

	controller.Success(c, "")
}
